#!/bin/bash
# 函数定义：记录日志
log_success() {
    echo "$(date +'%Y-%m-%d %H:%M:%S') $1"
}


# 使用初始化选项重新初始化 PostgreSQL
sudo postgresql-setup initdb
log_success "PostgreSQL 数据库初始化成功."

# 重启启动 PostgreSQL 服务
sudo systemctl restart postgresql
log_success "重启动 PostgreSQL 服务成功."

# 设置密码
sudo -i -u postgres psql -c "ALTER USER postgres PASSWORD '123456';"
log_success "设置 PostgreSQL 密码成功."

# 创建数据库
sudo  -i -u postgres psql -c "CREATE DATABASE sysbench;"
log_success "创建数据库成功."

# 创建用户并授予权限
sudo  -i -u postgres psql -c "CREATE USER sysbench WITH ENCRYPTED PASSWORD '123456';"
sudo  -i -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE sysbench TO sysbench;"
log_success "创建用户并授予权限成功."

# 要添加的规则
RULE="host         all             all          0.0.0.0/0    md5"

# PostgreSQL 数据目录路径
PG_DATA_DIR="/var/lib/pgsql/data"

# pg_hba.conf 文件路径
PG_HBA_CONF="$PG_DATA_DIR/pg_hba.conf"

# 检查 pg_hba.conf 文件是否存在
if [ ! -f "$PG_HBA_CONF" ]; then
    echo "Error: pg_hba.conf file not found at $PG_HBA_CONF"
    exit 1
fi

# 检查规则是否已经存在
if grep -q "$RULE" "$PG_HBA_CONF"; then
    echo "规则 $RULE 已经存在于 $PG_HBA_CONF 文件中，不进行修改。"
else
    # 将规则添加到 pg_hba.conf 文件
    echo "$RULE" | sudo tee -a "$PG_HBA_CONF" > /dev/null
    echo "成功添加规则到 $PG_HBA_CONF 文件。"
fi

# 设置变量
CONF_FILE="/var/lib/pgsql/data/postgresql.conf"
LISTEN_ADDRESSES="'*'"
PORT="5432"

# 检查是否已经修改过 listen_addresses 和 port
if grep -q "^listen_addresses" "$CONF_FILE" && grep -q "^port" "$CONF_FILE"; then
    echo "listen_addresses 和 port 已经修改过，跳过执行。"
else

    # 设置 listen_addresses 和 port 的值
    sed -i "s/#listen_addresses = 'localhost'/listen_addresses = ${LISTEN_ADDRESSES}/" "$CONF_FILE"
    sed -i "s/#port = 5432/port = ${PORT}/" "$CONF_FILE"

    # 修改 postgresql.conf 文件
    sed -i "/^#listen_addresses/s/^#//" "$CONF_FILE"
    sed -i "/^#port/s/^#//" "$CONF_FILE"

   

    echo "成功修改 postgresql.conf 文件。"
fi

